
//@flow

/**
 * 版本检查
 */
import React, { Component } from 'react';
import { 
    View,
    Linking,
    ActivityIndicator,
    Text,
    Image,
    TouchableHighlight,
    StyleSheet,
 } from 'react-native';
import { 
    Button, Progress,Modal,
 } from "antd-mobile-rn";
import { connect } from "react-redux";
import { DownloadProgress,RemotePackage } from "react-native-code-push";
import { UpdateStatus,LastestVersionSource, VersionState } from "./version.state";
import * as action from "./version.action";
import { linkToAppStore } from '../../util/common';
type VersionProps = {
    //redux
    checkingUpdate : ()=>{},//检查更新
    propgress	   : number,//下载更新进度
    bundleVersion  : string,//code push 版本
    label          : string,//提示语
    status         : UpdateStatus,//更新处于哪个状态
    des            : string,//更新的内容预览
    lastestVersion : string,//新版本号
    size           : number,//新版本的大小，可能是bundle包的大小，也可能是二进制包的大小
    fromSource     : LastestVersionSource,//新版本来源商店还是服务器
    isMandatory    : boolean,//是否强制更新
    onDownloadClick: ()=>{},//点击下载code push包
    remotePackage  : RemotePackage,
}
type State = {
    show : boolean,//是否显示蒙层
}
type UpdateBtnItemType = {
    title : string,
    action : ()=>{}
}
type UpdateBtnType = {
    [key:LastestVersionSource] : UpdateBtnItemType,
}
class Version extends Component <VersionProps,State>{
    /** 初始化 state*/
    state : State = {
        show : true,
    }
    /**渲染头部视图+版本号 */
    renderHeaderWithVersion(bindary:string,bundle:string,tipLabel:string){
        return (
            <View style={styles.header}>
                {this.renderBg(require('../../resource/version_bg.png'))}
                <Text style={styles.headerText}>{tipLabel}{this.showVersion(bindary,bundle)}</Text>
            </View>
        )
    }
    /**判断是否在标题显示版本 */
    showVersion(bindary:string,bundle:string){
        let bindaryVersion : Array<number> ;
        let bundleVersion : string;
        try {
            bindaryVersion = bindary.split('.');
            if(bindaryVersion.length == 3){
                if(bindaryVersion[0]==0 && bindaryVersion[1]==0 && bindaryVersion[2]==0){
                    //三个版本号同时为零，是不可能的，所以不显示
                    throw new Error('不显示')
                }
            }
            bundleVersion = bundle.replace('v','')
            if(bundleVersion == 0){
                throw new Error('不显示，因为label为0');
            }
        }catch(error) {
            return ''
        }
        return `v${bindary}.${bundleVersion}`
    }
    /**渲染底部按钮
     * codepush 更新
     *  强制更新：只有一个立即更新
     *  非强制 : 暂不更新 + 立即更新
     * app store版本
     *  等于非强制更新
     */
    renderFooter(updateSource:LastestVersionSource,isMandatory:boolean,updateStatus:UpdateStatus){
        let updateBtn :UpdateBtnItemType;
        let updateBtnItem : UpdateBtnType= {
            [LastestVersionSource.FROM_APP_STORE]:{
                title : '前往app store',
                action : ()=>{
                    /**跳转到应用商店 */
                    linkToAppStore()
                }
            },
            [LastestVersionSource.FROM_CODE_PUSH]:{
                title:'立即更新',
                action:()=>{
                    this.props.onDownloadClick(this.props.remotePackage)
                }
            }
        }
        updateBtn = updateBtnItem[updateSource];


        let footer = (
            <View style={styles.footerContainer}>
                {
                    isMandatory ? null
                                : <Button style={styles.footerBtnStyle} size="small" onClick={()=>{this.setState({show:false})}}>暂不更新</Button>
                }
                <Button onClick={updateBtn.action} style={styles.footerBtnStyle} type="primary" size="small">{updateBtn.title}</Button>
            </View>
        )
        return (updateStatus == UpdateStatus.AppStoreHasUpdate || updateStatus== UpdateStatus.CodePushHasUpdate) ?footer : null
    }
    /**渲染检查状态 
     * 1，检查状态
     * 2，正在安装
    */
    renderNormalText(text:string){
        return (
            <View style={styles.textLoading}>
                <ActivityIndicator animating={true}/>
                <Text>{text}</Text>
            </View>
        )
    }
    /**渲染检测新版本，内容描述 */
    renderLatestDesc(des:string){

        let arr:Array<string> = des.split('\n');
        return (
            <View>
                {
                    arr.map(item=>{
                        return <Text style={styles.desc} key={item}>{item}</Text>
                    })
                }
            </View>
        )
    }
    /**渲染下载状态 */
    renderDownload(progress:number){
        let percent : number = parseInt(progress) ;
        return (
            <View style={styles.progressContainer}>
                <Progress percent={percent}
                         position="normal"
                         style={styles.progress}
                         barStyle={styles.progress}
                         unfilled={true}/>
            </View>
        )
    }
    /**
     * 加载中的时候需要显示进度条，其他简单文字显示即可
     * @param {*} props 
     */
    renderBody(props:VersionProps){
        let status :UpdateStatus = props.status;
        switch(status){
            case UpdateStatus.CodePushDownloadingUpdate:
                return this.renderDownload(props.propgress)
            case UpdateStatus.AppStoreHasUpdate:
            case UpdateStatus.CodePushHasUpdate:
                return this.renderLatestDesc(props.des)
            default :
                return this.renderNormalText(props.label)
        }
    }
    /**渲染背景图 */
    renderBg(img:any){
        return (
            <Image 
                style={styles.bgImg}
                resizeMode="stretch"
                source={img}/>
        )
    }
    render(){
        /**
         * 隐藏当前蒙层的情况
         * 1，确认检查不到任何更新
         * 2，有更新但是不是强制更新内容，用户点击了暂不更新
         */
        let isShow = this.props.status!=UpdateStatus.CodePushNotUpdate && this.state.show
        return (
            <Modal
                transparent={true}
                popup={true}
                animationType="slide-up"
                style={styles.container}
                visible={isShow}>
                <View>
                    {this.renderHeaderWithVersion(this.props.lastestVersion,this.props.bundleVersion,this.props.label)}
                    <View style={styles.body}>
                        {this.renderBody(this.props)}
                    </View>
                    {this.renderFooter(this.props.fromSource,this.props.isMandatory,this.props.status)}
                </View>
            </Modal>
        )
    }

}
const mapStateToProps = (state,ownProps):VersionProps=>{
    let versionState : VersionState = state.versionReducer;

    return {
        propgress : versionState.downloadProgress,//下载进度
        label:versionState.tipLabel,//提示语
        status:versionState.updateState,
        des:versionState.lastestDes,
        lastestVersion:versionState.latestAppVersion,
        bundleVersion : versionState.latestCodePushLabel,
        size:versionState.lastestSize,
        fromSource:versionState.fromSource,
        isMandatory:versionState.isMandatory,
        remotePackage : versionState.remotePackage,
        
    }
}
const mapDispatchToProps = (dispatch):VersionProps=>{
    return {
        checkingUpdate:dispatch(action.setupChecking()),
        onDownloadClick:(rPackage:RemotePackage)=>dispatch(action.onDownloadClick(rPackage))
    }
}
Version = connect(mapStateToProps,mapDispatchToProps)(Version);
export {Version};

const styles = StyleSheet.create({
    footerBtnStyle:{
        flex:1,
        height:30,
        borderRadius: 15,
        // margin: 10,
        marginTop:20,

    },
    footerContainer:{
        // flex:1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent:'center'
    },
    container:{
        // flex:1,
        // paddingHorizontal: 13,
        // paddingVertical: 20,
        // alignItems: 'center',
        // justifyContent: 'center',
        overflow:'visible'
    },
    textLoading:{
        flexDirection:'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 20,
    },
    header:{
        alignItems:'center',
        justifyContent:'center',
        // overflow: 'visible',
        // backgroundColor: 'rgba(0,0,0,0.5)',
        height:50,
    },
    headerText:{
        fontSize:22,
        fontWeight: '700',
        color:'rgb(50,50,50)',
        shadowColor: 'white',
        
    },
    bgImg:{
        width:'100%',
        height:100,
        position:'absolute',
        top: -50,
    },
    body:{
        marginTop:10
    },
    desc:{
        color:'gray',
        marginTop:5,
        // backgroundColor: 'red',
    },
    progressContainer:{
        width:'100%',
        height:30,
    },
    progress:{
        height:'100%'
    }
})